package com.dataextend.controller;

import com.alibaba.fastjson.JSONObject;
import com.dataextend.entity.*;
import com.dataextend.service.*;
import com.dataextend.utils.*;
import com.dataextend.config.jwt.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Api(value = "用户表接口")
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins={"http://localhost:8080"},allowCredentials="true")
public class RootUserController extends RootBaseApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @ApiOperation("添加用户")
//    @RequiresPermissions("user:add")
    @PostMapping("/add")
    public Map<String, Object> add(@RequestParam(value = "user", required = false) String user,
                                   @RequestParam(value = "password", required = false) String password,
                                   @RequestParam(value = "name", required = false) String name,
                                   @RequestParam(value = "status", required = false) Integer status)
    {
        UserEntity userEntity = new UserEntity()
                .setUser(user)
                .setPassword(password)
                .setName(name)
                .setStatus(status)
                .setCreateTime(new DateUtils().getDateTime())
                .setUpdateTime(new DateUtils().getDateTime())
                .setLastLoginTime(new DateUtils().getDateTime());

        if (userService.add(userEntity)==0) {
            return resp(406,"添加失败");
        } else {
            return resp(200, "添加成功", userEntity);
        }
    }

    @ApiOperation("修改用户信息")
//    @RequiresPermissions("user:update")
    @PostMapping("/update")
    public Map<String, Object> update(@RequestParam(value = "id", required = false) Long id,
                                      @RequestParam(value = "user", required = false) String user,
                                      @RequestParam(value = "password", required = false) String password,
                                      @RequestParam(value = "name", required = false) String name,
                                      @RequestParam(value = "status", required = false) Integer status) {
        UserEntity userEntity = new UserEntity()
                .setId(id)
                .setUser(user)
                .setPassword(password)
                .setName(name)
                .setStatus(status)
                .setUpdateTime(new DateUtils().getDateTime());

        return resp(200, "修改成功", userService.update(userEntity));
    }

    @ApiOperation("删除用户")
//    @RequiresPermissions("user:delete")
    @PostMapping("/delete")
    public Map<String, Object> deleteById(@RequestParam(value = "id", required = false) Long id) {
        // 删除用户前先删除用户角色
        List<UserRoleEntity> userRoleEntityList = userRoleService.list(new UserRoleEntity().setUserId(id));
        for (UserRoleEntity ur: userRoleEntityList) {
            userRoleService.delete(ur.getId());
        }
        userService.delete(id);
        return resp(200, "删除成功");
    }

    @ApiOperation("根据id查询用户信息")
//    @RequiresPermissions("user:query")
    @GetMapping("/query")
    public Map<String, Object> queryById(@RequestParam(value = "id", required = false) Long id) {
        return resp(200, "查询成功", userService.queryById(id));
    }

    @ApiOperation("查询所有用户信息")
//    @RequiresPermissions("user:list")
    @GetMapping("/list")
    public Map<String, Object> list(@RequestParam(value = "pageNum", required = false) int pageNum,
                                    @RequestParam(value = "pageSize", required = false) int pageSize)
    {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("id asc");
        List<UserEntity> list = userService.list();
        PageInfo<UserEntity> pageInfo =  new PageInfo<UserEntity>(list);
        return resp(200, "查询所有成功", pageInfo);
    }

    @ApiOperation("根据账号查询用户")
    @GetMapping("/query/user")
    public Map<String, Object> queryByName(String user) {
        return resp(200, "查询成功", userService.queryByUser(user));
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")   // @RequestParam(value = "dataDate", required = false) String dataDate
    public Map<String, Object> login (HttpServletResponse response, @RequestParam(value = "user", required = false) String user,
                                      @RequestParam(value = "password", required = false) String password) throws IOException {
        UserEntity userEntity = userService.queryByUser(user);
        // 判断用户是否存在
        if (userEntity != null) {
            // 判断用户是否有效， 0有效 1无效
            if (userEntity.getStatus().equals(0)) {
                if (password.equals(userEntity.getPassword())) {
                    // 设置 cookie 发送到客户端
                    Cookie cookie = new Cookie("token", URLEncoder.encode(JwtUtil.sign(user, password),"UTF-8"));
                    // cookie.setMaxAge(5 * 60 * 24);
                    cookie.setPath("/");
                    response.addCookie(cookie);

                    // 修改登陆时间
                    UserEntity userEntity1 = new UserEntity();
                    userEntity1.setId(userEntity.getId());
                    userEntity1.setLastLoginTime(new DateUtils().getDateTime());
                    userService.update(userEntity1);
                    String token = String.valueOf(URLEncoder.encode(JwtUtil.sign(user, password),"UTF-8")) + "; Path=/";

                    JSONObject returnResult = new JSONObject(true);
                    String createTime = userEntity.getCreateTime();
                    Long id = userEntity.getId();
                    String lastLoginTime = new DateUtils().getDateTime();
                    String name = userEntity.getName();
                    Integer status = userEntity.getStatus();
                    String updateTime = userEntity.getUpdateTime();
                    returnResult.put("createTime", createTime);
                    returnResult.put("id", id);
                    returnResult.put("lastLoginTime", lastLoginTime);
                    returnResult.put("name", name);
                    returnResult.put("status", status);
                    returnResult.put("updateTime", updateTime);
                    returnResult.put("user", user);
                    returnResult.put("token", token.replace(" Path=/",""));

                    // 更新登陆时间
                    userEntity.setLastLoginTime(new DateUtils().getDateTime());
                    return resp(200,"登录成功", returnResult);   // userEntity  returnResult
                } else {
                    return resp(10011,"密码错误");
                }
            } else { return resp(10000, "抱歉该用户无效"); }
        }
        return resp(10001, "没有该用户");
    }

    @ApiOperation("用户退出登录")
    @GetMapping("/logout")
    public Map<String, Object> logout(HttpServletRequest request, HttpServletResponse response) {
        JwtUtil.signOut(request, response);
        return resp(200, "退出登录成功");
    }
}
